<template>
  <div class="course-content">
    <h2>学习内容编辑</h2>
    <CourseChoose 
      :courseInfo="courseInfo || null" 
      :autoQueryParams="autoQueryParams"
      @course-selected="onCourseSelected" 
    />
    <div v-if="selectedCourse" class="content-section">
      <h3>章节内容</h3>
      <div v-for="(chapter, idx) in chapters" :key="chapter.id" class="chapter-item">
        <div class="chapter-fields">
          <label>章节名称：</label>
          <input v-model="chapter.content" placeholder="请输入章节名称" />

          <label>教学方法：</label>
          <input v-model="chapter.method" placeholder="请输入教学方法" />

          <div class="goal-checkbox-group">
            <label style="display: block;">课程目标：</label>
            <div >
              <label v-for="goal in courseGoals" :key="goal.id" class="goal-checkbox">
                <input type="checkbox" :value="goal.id" v-model="chapter.goal" :disabled="courseGoals.length === 0" />
                {{ goal.text }}
              </label>
            </div>
            
          </div>

          <div class="row-flex">
            <label>思政元素：</label>
            <input v-model="chapter.political_element" placeholder="请输入思政元素" />
            <label>学时：</label>
            <input v-model.number="chapter.period" type="number" min="0" step="0.1" @blur="formatPeriod(idx)" placeholder="请输入学时" style="width: 80px;" />
          </div>
        </div>
        <div class="chapter-actions">
          <el-button @click="removeChapter(idx)" type="danger" size="small" plain>删除章节</el-button>
        </div>
      </div>
      <div class="chapter-summary">
        <span>总学时：{{ totalPeriod }} / {{ courseTotalPeriod }}</span>
        <span v-if="totalPeriod !== courseTotalPeriod" style="color:red;">（总学时需等于课程总学时）</span>
      </div>
      <el-button @click="addChapter" type="primary" plain>添加章节</el-button>
      <el-button @click="saveContent" type="success" :loading="saving">保存内容</el-button>
      <el-button @click="handleNext" type="warning" :disabled="!selectedCourse">下一项</el-button>
    </div>
  </div>
</template>

<script>
import CourseChoose from './CourseChoose.vue';
import { courseApi } from '../api/index.js';

export default {
  name: 'CourseContent',
  components: { CourseChoose },
  props: {
    courseInfo: {
      type: Object,
      default: null
    },
    autoQueryParams: {
      type: Object,
      default: null
    }
  },
  emits: ['next-step'],
  data() {
    return {
      selectedCourse: null,
      chapters: [],
      courseGoals: [], // 课程目标列表，通过API获取
      courseTotalPeriod: 0, // 课程总学时，从课程信息获取
      saving: false, // 保存状态
    };
  },
  computed: {
    totalPeriod() {
      return this.chapters.reduce((sum, c) => sum + (parseFloat(c.period) || 0), 0).toFixed(1);
    },
  },
  watch: {
    // 监听props变化，如果有课程信息则自动选择
    courseInfo: {
      handler(newCourseInfo) {
        if (newCourseInfo && Object.keys(newCourseInfo).length > 0 && newCourseInfo.id) {
          this.onCourseSelected(newCourseInfo);
        } else {
          // 如果没有有效的课程信息，清空状态
          this.selectedCourse = null;
          this.chapters = [];
        }
      },
      immediate: true
    }
  },
  methods: {
    async onCourseSelected(course) {
      console.log('CourseContent onCourseSelected:', { course });
      this.selectedCourse = course;
      this.chapters = []; // 清空章节列表
      
      // console.log('选中的课程信息:', course); // 调试信息
      
      // 尝试获取课程ID，可能在不同的字段中
      const courseId = course._id || course.id || course.courseId;
      
      if (course && courseId) {
        try {
          // 查询课程目标
          await this.loadCourseGoals(courseId);
          // 查询已有的章节内容（包含总学时信息）
          await this.loadCourseContent(courseId);
        } catch (error) {
          console.error('加载课程信息失败:', error);
          alert('加载课程信息失败，请重试');
        }
      } else {
        console.warn('未找到课程ID，无法加载课程目标');
        this.courseGoals = [];
        this.courseTotalPeriod = 0;
      }
    },

    /**
     * 加载课程目标列表
     * @param {string} id - 课程ID,此处为mongodb给的id，而不是教务处给的id
     */
    async loadCourseGoals(id) {
      try {
        const response = await courseApi.queryCourseGoals(id);
        
        if (response.success===0) {
          // 返回结果中data直接就是目标列表，没有嵌套
          const goalList = response.data || [];
          // 将返回的目标名称列表转换为组件需要的格式
          this.courseGoals = goalList.map((goalName, index) => ({
            id: String(index + 1),
            text: goalName
          }));
        } else {
          console.error('查询课程目标失败:', response.message);
          this.courseGoals = [];
        }
      } catch (error) {
        console.error('查询课程目标异常:', error);
        this.courseGoals = [];
      }
    },

    /**
     * 加载课程章节内容
     * @param {string} id - 课程ID（mongodb的_id）
     */
    async loadCourseContent(id) {
      try {
        const response = await courseApi.queryCourseContent(id);
        
        if (response.success===0) {
          // 设置课程总学时（从接口返回的total_period字段获取）
          this.courseTotalPeriod = response.data.total_period || 0;
          
          if (response.data.content_relation && response.data.content_relation.length > 0) {
            // 将返回的章节内容转换为组件需要的格式
            this.chapters = response.data.content_relation.map((chapter, index) => ({
              content: chapter.content || '',
              method: chapter.method || '',
              goal: chapter.goal || [], // 课程目标ID数组
              political_element: chapter.political_element || '',
              period: chapter.period ? chapter.period.toString() : ''
            }));
            // console.log('加载的章节内容:', this.chapters);
          } else {
            // console.log('该课程暂无章节内容');
            this.chapters = [];
          }
        } else {
          console.log('该课程暂无章节内容');
          this.chapters = [];
          this.courseTotalPeriod = 0;
        }
      } catch (error) {
        console.error('查询课程内容异常:', error);
        this.chapters = [];
        this.courseTotalPeriod = 0;
      }
    },
    addChapter() {
      this.chapters.push({
        content: '',
        method: '',
        goal: [],
        political_element: '',
        period: '',
      });
    },
    removeChapter(idx) {
      this.chapters.splice(idx, 1);
    },
    formatPeriod(idx) {
      let val = this.chapters[idx].period;
      if (val === '' || val === null) return;
      let num = parseFloat(val);
      if (isNaN(num)) num = 0;
      this.chapters[idx].period = num.toFixed(1);
    },
    async saveContent() {
      // 验证总学时
      if (parseFloat(this.totalPeriod) !== this.courseTotalPeriod) {
        alert('所有章节学时之和需等于课程总学时！');
        return;
      }

      // 验证是否有选中的课程
      if (!this.selectedCourse) {
        alert('请先选择课程！');
        return;
      }

      // 验证是否有章节内容
      if (this.chapters.length === 0) {
        alert('请至少添加一个章节！');
        return;
      }

      // 验证章节数据完整性
      for (let i = 0; i < this.chapters.length; i++) {
        const chapter = this.chapters[i];
        if (!chapter.content.trim()) {
          alert(`第${i + 1}个章节的章节名称不能为空！`);
          return;
        }
        if (!chapter.method.trim()) {
          alert(`第${i + 1}个章节的教学方法不能为空！`);
          return;
        }
        if (!chapter.period || parseFloat(chapter.period) <= 0) {
          alert(`第${i + 1}个章节的学时必须大于0！`);
          return;
        }
      }

      this.saving = true;
      
      try {
        // 获取课程ID
        const courseId = this.selectedCourse._id || this.selectedCourse.id || this.selectedCourse.courseId;
        
        if (!courseId) {
          alert('无法获取课程ID，保存失败！');
          return;
        }

        // 准备保存数据
        const contentRelation = this.chapters.map(chapter => ({
          content: chapter.content.trim(),
          method: chapter.method.trim(),
          goal: chapter.goal || [], // 支撑的课程目标ID数组
          political_element: chapter.political_element.trim(),
          period: parseFloat(chapter.period)
        }));

        const saveParams = {
          courseId: courseId,
          content_relation: contentRelation
        };

        ///console.log('保存参数:', saveParams); // 调试信息

        // 调用保存接口
        const response = await courseApi.saveCourseContent(saveParams);
        
        if (response.success === 0) {
          alert('保存成功！');
        } else {
          alert(`保存失败：${response.err || '未知错误'}`);
        }
              } catch (error) {
          console.error('保存课程内容失败:', error);
          alert('保存失败，请检查网络连接或稍后重试');
        } finally {
          this.saving = false;
        }
      },
      
          handleNext() {
      console.log('CourseContent handleNext:', { selectedCourse: this.selectedCourse });
      
      // 检查是否有选中的课程
      if (!this.selectedCourse || !this.selectedCourse.id) {
        this.$message.warning('请先选择课程');
        return;
      }
      
      // 构建要传递的课程信息，包含自动查询所需的参数
      const courseInfo = {
        ...this.selectedCourse,
        grade: this.selectedCourse.grade || this.selectedCourse.year,
        major: this.selectedCourse.major || this.selectedCourse.majorName,
        courseId: this.selectedCourse.courseId || this.selectedCourse.id,
        courseName: this.selectedCourse.courseName || this.selectedCourse.name
      }
      
      // 触发下一项事件
      this.$emit('next-step', 'course-5', courseInfo);
    },
  },
};
</script>

<style scoped>
.course-content {
  padding: 24px;
  color: #333; /* 设置默认文字颜色为深灰色 */
}

.course-content h2 {
  color: #333; /* 确保主标题颜色正常 */
}
.content-section {
  margin-top: 32px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.content-section h3 {
  color: #333; /* 确保章节内容标题颜色正常 */
}
.chapter-item {
  margin-bottom: 18px;
  padding: 12px;
  background: #f9f9f9;
  border-radius: 6px;
}
.chapter-fields {
  display: flex;
  flex-wrap: wrap;
  gap: 10px 16px;
  align-items: center;
}
.chapter-fields label {
  min-width: 80px;
  color: #333; /* 确保标签文字颜色正常 */
}
.chapter-fields input,
.chapter-fields select {
  min-width: 120px;
  padding: 4px 8px;
  color: #333; /* 确保输入框文字颜色正常 */
}
.chapter-fields select[multiple] {
  min-width: 180px;
  height: 60px;
}
.chapter-summary {
  margin-bottom: 12px;
  font-weight: bold;
  color: #333; /* 确保摘要文字颜色正常 */
}
.save-btn {
  margin-left: 16px;
  background: #409eff;
  color: #fff;
  border: none;
  padding: 6px 18px;
  border-radius: 4px;
  cursor: pointer;
}
.save-btn:hover {
  background: #337ecc;
}
.goal-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 16px;
  min-width: 180px;
}
.goal-checkbox {
  display: flex;
  align-items: center;
  margin-right: 12px;
  color: #333; /* 确保复选框标签文字颜色正常 */
}
.row-flex {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
  margin-bottom: 0;
}
.chapter-actions {
  margin-top: 8px;
}
</style>